// src/main/java/com/bookmanager/dao/UserDAO.java
package com.bookmanager.dao;

import com.bookmanager.model.User;
import com.bookmanager.util.DatabaseUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {

    public User getUserById(String userId) {
        String sql = "SELECT * FROM users WHERE user_id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return extractUserFromResultSet(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public User login(String userId, String password) {
        String sql = "SELECT * FROM users WHERE user_id = ? AND password = ?";
        System.out.println("🔍 登录查询: userId=" + userId + ", password=" + password); // 添加日志

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                System.out.println("✅ 登录成功，用户: " + rs.getString("username"));
                return extractUserFromResultSet(rs);
            } else {
                System.out.println("❌ 登录失败，用户ID或密码错误");
            }
        } catch (SQLException e) {
            System.out.println("❌ 数据库查询错误: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public boolean addUser(User user) {
        String sql = "INSERT INTO users (user_id, username, password, email, phone, role) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, user.getUserId());
            stmt.setString(2, user.getUsername());
            stmt.setString(3, user.getPassword());
            stmt.setString(4, user.getEmail());
            stmt.setString(5, user.getPhone());
            stmt.setString(6, user.getRole());

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    private User extractUserFromResultSet(ResultSet rs) throws SQLException {
        User user = new User();
        user.setUserId(rs.getString("user_id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setEmail(rs.getString("email"));
        user.setPhone(rs.getString("phone"));
        user.setRole(rs.getString("role"));
        user.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
        return user;
    }

    public boolean registerUser(User user) {
        String sql = "INSERT INTO users (user_id, username, password, email, phone, role) VALUES (?, ?, ?, ?, ?, ?)";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, user.getUserId());
            stmt.setString(2, user.getUsername());
            stmt.setString(3, user.getPassword());
            stmt.setString(4, user.getEmail());
            stmt.setString(5, user.getPhone());
            stmt.setString(6, user.getRole());

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            // 处理重复用户ID的情况
            if (e.getMessage().contains("Duplicate entry")) {
                System.out.println("❌ 用户ID已存在: " + user.getUserId());
            }
        }
        return false;
    }

    // 添加检查用户是否存在的方法
    public boolean isUserIdExists(String userId) {
        String sql = "SELECT COUNT(*) FROM users WHERE user_id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public List<User> getAllUsers() {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM users ORDER BY create_time DESC";

        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                users.add(extractUserFromResultSet(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    public boolean updateUser(User user) {
        String sql;
        boolean updatePassword = user.getPassword() != null && !user.getPassword().trim().isEmpty();

        if (updatePassword) {
            // 更新包括密码的所有信息
            sql = "UPDATE users SET username = ?, password = ?, email = ?, phone = ?, role = ? WHERE user_id = ?";
        } else {
            // 不更新密码
            sql = "UPDATE users SET username = ?, email = ?, phone = ?, role = ? WHERE user_id = ?";
        }

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            if (updatePassword) {
                stmt.setString(1, user.getUsername());
                stmt.setString(2, user.getPassword());
                stmt.setString(3, user.getEmail());
                stmt.setString(4, user.getPhone());
                stmt.setString(5, user.getRole());
                stmt.setString(6, user.getUserId());
            } else {
                stmt.setString(1, user.getUsername());
                stmt.setString(2, user.getEmail());
                stmt.setString(3, user.getPhone());
                stmt.setString(4, user.getRole());
                stmt.setString(5, user.getUserId());
            }

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean resetPassword(String userId, String newPassword) {
        String sql = "UPDATE users SET password = ? WHERE user_id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, newPassword);
            stmt.setString(2, userId);

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 搜索用户
    public List<User> searchUsers(String keyword) {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM users WHERE user_id LIKE ? OR username LIKE ? OR email LIKE ? ORDER BY create_time DESC";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            String likeKeyword = "%" + keyword + "%";
            stmt.setString(1, likeKeyword);
            stmt.setString(2, likeKeyword);
            stmt.setString(3, likeKeyword);

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                users.add(extractUserFromResultSet(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    // 更新用户角色
    public boolean updateUserRole(String userId, String newRole) {
        String sql = "UPDATE users SET role = ? WHERE user_id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, newRole);
            stmt.setString(2, userId);

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除用户
     * @param userId 用户ID
     * @return 删除是否成功
     */
    public boolean deleteUser(String userId) {
        String sql = "DELETE FROM users WHERE user_id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("❌ 删除用户失败: " + e.getMessage());
            // 处理外键约束等数据库错误
            if (e.getMessage().contains("foreign key constraint")) {
                System.out.println("⚠️ 该用户有关联数据，无法直接删除");
            }
        }
        return false;
    }

    /**
     * 检查用户是否有借阅记录或其他关联数据
     * @param userId 用户ID
     * @return 是否存在关联数据
     */
    public boolean hasRelatedData(String userId) {
        // 检查借阅记录
        String borrowSql = "SELECT COUNT(*) FROM borrow_records WHERE user_id = ? AND return_time IS NULL";
        // 检查收藏记录
        String favoriteSql = "SELECT COUNT(*) FROM favorites WHERE user_id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement borrowStmt = conn.prepareStatement(borrowSql);
             PreparedStatement favoriteStmt = conn.prepareStatement(favoriteSql)) {

            // 检查未归还的借阅记录
            borrowStmt.setString(1, userId);
            ResultSet borrowRs = borrowStmt.executeQuery();
            if (borrowRs.next() && borrowRs.getInt(1) > 0) {
                return true; // 有未归还的图书
            }

            // 检查收藏记录
            favoriteStmt.setString(1, userId);
            ResultSet favoriteRs = favoriteStmt.executeQuery();
            if (favoriteRs.next() && favoriteRs.getInt(1) > 0) {
                return true; // 有收藏记录
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}